package com.asen.commons.core.jdbc.result;

import com.asen.commons.utils.BaseAssert;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.jdbc.core.RowMapper;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * 查询结果处理
 *
 * @author Gary
 * @version 1.0
 * @date 2018-12-05
 */
public class BaseResultSetExtractor<T> implements ResultSetExtractor<List<T>> {

    private final Class<T> clazz;

    private final RowMapper<T> rowMapper;

    public BaseResultSetExtractor(Class<T> clazz) {
        this(clazz, new BaseRowMapper<T>(clazz));
    }

    public BaseResultSetExtractor(Class<T> clazz, RowMapper<T> rowMapper) {
        BaseAssert.notNull(rowMapper, "RowMapper不能为空");
        this.clazz = clazz;
        this.rowMapper = rowMapper;
    }

    @Override
    public List<T> extractData(ResultSet rs) throws SQLException {
        List<T> results = new ArrayList<T>();
        int rowNum = 0;
        while (rs.next()) {
            results.add(this.rowMapper.mapRow(rs, rowNum++));
        }
        process(results);
        return results;
    }

    private void process(List<T> results) throws SQLException {
        if (results == null || results.isEmpty()) {
            return;
        }
        Set<ResultProcessor> set = null;

        try {
            set = ResultProcessorRegistry.getProcessors(clazz);
            if (set == null || set.isEmpty()) {
                return;
            }
            for (ResultProcessor processor : set) {
                processor.process(results);
            }
        } catch (Exception e) {
            throw new SQLException("handle processors " + set + " error.", e);
        }
    }
}
